<?php
// bsf管理模板函数文件

/**
 * 给树状菜单添加level并去掉没有子菜单的菜单项
 * @param  array   $data  [description]
 * @param  integer $root  [description]
 * @param  string  $child [description]
 * @param  string  $level [description]
 */
function memuLevelClear($data, $root=1, $child='child', $level='level')
{
    if (is_array($data)) {
        foreach($data as $key => $val){
        	$data[$key]['selected'] = false;
        	$data[$key]['level'] = $root;
        	if (!empty($val[$child]) && is_array($val[$child])) {
				$data[$key][$child] = memuLevelClear($val[$child],$root+1);
        	}else if ($root<3&&$data[$key]['menu_type']==1) {
        		unset($data[$key]);
        	}
        	if (empty($data[$key][$child])&&($data[$key]['level']==1)&&($data[$key]['menu_type']==1)) {
        		unset($data[$key]);
        	}
        }
        return array_values($data);
    }
    return array();
}

/**
 * [rulesDeal 给树状规则表处理成 module-controller-action ]
 * @AuthorHTL
 * @DateTime  2017-01-16T16:01:46+0800
 * @param     [array]                   $data [树状规则数组]
 * @return    [array]                         [返回数组]
 */
function rulesDeal($data)
{   
    if (is_array($data)) {
        $ret = [];
        foreach ($data as $k1 => $v1) {
            $str1 = $v1['name'];
            if (is_array($v1['child'])) {
                foreach ($v1['child'] as $k2 => $v2) {
                    $str2 = $str1.'-'.$v2['name'];
                    if (is_array($v2['child'])) {
                        foreach ($v2['child'] as $k3 => $v3) {
                            $str3 = $str2.'-'.$v3['name'];
                            $ret[] = $str3;
                        }
                    }else{
                        $ret[] = $str2;
                    }
                }
            }else{
                $ret[] = $str1;
            }
        }
        return $ret;
    }
    return [];
}

/**
 * cookies加密函数
 * @param string 加密后字符串
 */
function encrypt($data, $key = 'kls8in1e') 
{ 
    $prep_code = serialize($data); 
    $block = mcrypt_get_block_size('des', 'ecb'); 
    if (($pad = $block - (strlen($prep_code) % $block)) < $block) { 
        $prep_code .= str_repeat(chr($pad), $pad); 
    } 
    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB); 
    return base64_encode($encrypt); 
} 

/**
 * cookies 解密密函数
 * @param array 解密后数组
 */
function decrypt($str, $key = 'kls8in1e') 
{ 
    $str = base64_decode($str); 
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); 
    $block = mcrypt_get_block_size('des', 'ecb'); 
    $pad = ord($str[($len = strlen($str)) - 1]); 
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) { 
        $str = substr($str, 0, strlen($str) - $pad); 
    } 
    return unserialize($str); 
}



/**
 * 运营商详情 - 
 * @return [type] [description]
 */
function report_detail($params){

    $api_url = 'http://api.qhweidai.com/api/Detailreport';
    $res = http_post($api_url,$params);
    return json_decode($res,true);

}

/**
 * 贷前申请 - 生成报告id
 * @return [type] [description]
 */
function preloan_apply($params){

    $api_url = 'http://api.qhweidai.com/api/watermelon';
    $res = http_post($api_url,$params);
    return json_decode($res,true);

}

/**
 * 贷前申请 - 报告详情
 * @return [type] [description]
 */
function preloan_report($param){

    $api_url = 'http://api.qhweidai.com/api/look_watermelon';

    $res = http_post($api_url,$param);
    return json_decode($res,true);

}

/**
 * 贷前申请 - 风险报告
 * @return [type] [description]
 */
function preloan_report_risk($param){

    $api_url = 'http://api.qhweidai.com/api/Riskgrade';
    $res = http_post($api_url,$param);
    return json_decode($res,true);
}


/**
 * 贷前申请 - 报告详情 西瓜分
 * @return [type] [description]
 */
function preloan_report_water($param, $is_test = true){

  $api_url = 'http://api.qhweidai.com/api/look_watermelon';

  $res = http_post($api_url,$param);
  return json_decode($res,true);

}

/**
 * GET 请求
 * @param string $url
 */
function http_get($url){
  $oCurl = curl_init();
  if(stripos($url,"https://")!==FALSE){
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  }
  curl_setopt($oCurl, CURLOPT_URL, $url);
  curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  $sContent = curl_exec($oCurl);
  $aStatus = curl_getinfo($oCurl);
  curl_close($oCurl);
  if(intval($aStatus["http_code"])==200){
    return $sContent;
  }else{
    return false;
  }
}

/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$param,$post_file=false){
  $oCurl = curl_init();
  if(stripos($url,"https://")!==FALSE){
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  }

  if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
    $is_curlFile = true;
  } else {
    $is_curlFile = false;
    if (defined('CURLOPT_SAFE_UPLOAD')) {
      curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
    }
  }
  if (is_string($param)) {
    $strPOST = $param;
  }elseif($post_file) {
    if($is_curlFile) {
      foreach ($param as $key => $val) {
        if (substr($val, 0, 1) == '@') {
          $param[$key] = new \CURLFile(realpath(substr($val,1)));
        }
      }
    }
    $strPOST = $param;
  } else {
    $aPOST = array();
    foreach($param as $key=>$val){
      $aPOST[] = $key."=".urlencode($val);
    }
    $strPOST =  join("&", $aPOST);
  }
  curl_setopt($oCurl, CURLOPT_URL, $url);
  curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt($oCurl, CURLOPT_POST,true);
  curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  $sContent = curl_exec($oCurl);
  $aStatus = curl_getinfo($oCurl);
  curl_close($oCurl);
  if(intval($aStatus["http_code"])==200){
    return $sContent;
  }else{
    return false;
  }
}




function curl_td($api_url, $params, $timeout, $connection_timeout){

  $options = array(
      CURLOPT_POST => 1,            // 请求方式为POST
      CURLOPT_URL => $api_url,      // 请求URL
      CURLOPT_RETURNTRANSFER => 1,  // 获取请求结果
    // -----------请确保启用以下两行配置------------
    // CURLOPT_SSL_VERIFYPEER => 1,  // 验证证书
    // CURLOPT_SSL_VERIFYHOST => 2,  // 验证主机名
    // -----------否则会存在被窃听的风险------------
      CURLOPT_POSTFIELDS => http_build_query($params) // 注入接口参数
  );
  if (defined("CURLOPT_TIMEOUT_MS")) {
    $options[CURLOPT_NOSIGNAL] = 1;
    $options[CURLOPT_TIMEOUT_MS] = $timeout;
  } else {
    $options[CURLOPT_TIMEOUT] = ceil($timeout / 1000);
  }
  if (defined("CURLOPT_CONNECTTIMEOUT_MS")) {
    $options[CURLOPT_CONNECTTIMEOUT_MS] = $connection_timeout;
  } else {
    $options[CURLOPT_CONNECTTIMEOUT] = ceil($connection_timeout / 1000);
  }
  $ch = curl_init();

  // curl_setopt ($ch, CURLOPT_CAINFO, getcwd().'/Public/cet/cacert.pem');


  curl_setopt_array($ch, $options);
  if(!($response = curl_exec($ch))) {
    // 错误处理，按照同盾接口格式fake调用结果
    return array(
        "success" => "false",
        "reason_code" => "000:调用API时发生错误[".curl_error($ch)."]"
    );
  }
  curl_close($ch);
  return json_decode($response, true);

}

function get_name_by_report_id($report_id){

  $name = M('preloan_apply','td_')->where(array('report_id'=>$report_id))->getfield('name');
  return $name?$name:'error!';
}



function getExpressInfo($expressNo = '')
{
    $testUrl            =   'https://poll.kuaidi100.com/test/poll/query.do';
    $productionUrl      =   'https://poll.kuaidi100.com/poll/query.do';
    $customer           =   'D56B33A29140CE3DC3B7EEE22130E3D3';
    $key                =   'SczrQHld120';

    $param['num']       =   $expressNo;
    $param['com']       =   'shunfeng';

    $data['customer']   =   $customer;
    $data['sign']       =   md5(json_encode($param).$key.$customer);
    $data['sign']       =   strtoupper($data['sign']);
    $data['param']      =   json_encode($param);
    $result = http_post($testUrl,$data);

    $result = json_decode($result,true);
    if($result['message'] == 'ok'){
        return  array('code'=>200,'data'=>$result['data']);
    }else{
        return  array('code'=>400,'data'=>$result['message']);
    }
}








